package com.demo11.d17_03.multiThread.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
 * @Author: root
 * @Date: 2018/12/4 18:46
 */
public class ServerThread implements Runnable {
    private Socket socket;

    private BufferedReader br;

    public ServerThread() {
    }

    public ServerThread(Socket socket) throws IOException {
        this.socket = socket;
        /**
         * 让程序通过该socket从中取出数据
         */
        br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    @Override
    public void run() {
        try {
            String content = null;
            while ((content = readFromClient()) != null) {
                for (Socket s : MyServer.socketList) {
                    PrintStream ps = new PrintStream(s.getOutputStream());
                    ps.println(content);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String readFromClient() {
        try {
            return br.readLine();
        } catch (IOException e) {
            MyServer.socketList.remove(socket);
        }
        return null;
    }
}
